<?php


namespace app\shopConsole\controller;


use app\BaseController;

use app\console\validate\TagValidate;
use app\lib\exception\ParamException;
use app\model\Tag;
use app\Request;
use app\shopConsole\service\tag\TagQueryService;
use app\shopConsole\service\tag\TagService;
use think\App;
use think\exception\ValidateException;

function shopTag2dict($list){
    $dateTime = app('DateTime');

    return [
        'id' => $list['id'],
        'name' => $list['name'],
        'shop_id' => $list['shop_id'],
        'create_time' => $list['create_time'],
        'update_time' => $list['update_time'],
        'format_create_time' => $dateTime->timestamp2date($list['create_time']),
        'format_update_time' => $dateTime->timestamp2date($list['update_time']),
    ];
}

//标签
class TagController extends BaseController
{

    public function create(Request $request, TagService $tagService)
    {
        $param = $request->param(['name']);
        $param['shop_id'] = $request->id;
        try
        {
            validate(TagValidate::class)
                ->scene('create')
                ->check($param);
        } catch (ValidateException $e) {
            throw new ParamException($e->getMessage());
        }

        $tag = $tagService->create($param);

        return $this->returnJson(shopTag2dict($tag));
    }

    public function get(Request $request, TagQueryService $tagQueryService)
    {
        $all = $request->get('all', false);
        $page = $request->get('page', 1);
        $perPage = $request->get('perPage', config('app.allow_limit'));

        if (!$all)
        {
            try
            {
                validate(TagValidate::class)
                    ->scene('get')
                    ->check([
                        'page'         => $page ,
                        'perPage'      => $perPage ,
                    ]);
            } catch (ValidateException $e) {
                throw new ParamException($e->getMessage());
            }
            $tag = $tagQueryService->getPageListByShopId($request->id, $page ,$perPage);
        }else{
            $tag = $tagQueryService->getListByShopId($request->id);
        }

        return $this->returnList(
            array_map(fn($list) => shopTag2dict($list), $tag['list']->toArray()),
            $tag['pagination']['page'], $tag['pagination']['perPage'], $tag['pagination']['total']
        );
    }

    public function update(Request $request, TagService $tagService)
    {
        $name = $request->param('name', '');

        if (empty($name))
        {
            throw new ParamException('未修改任何数据');
        }

        $tag = $tagService->update($name);

        return $this->returnJson(shopTag2dict($tag));
    }

    public function delete(TagService $tagService)
    {
        $tagService->delete();
        return $this->returnJson();
    }

    public function getById(Tag $tag)
    {
        return $this->returnJson(shopTag2dict($tag));
    }

}